package net.oschina.archx.spring.sequoiadb.session;

import com.sequoiadb.base.DBCursor;
import com.sequoiadb.base.Sequoiadb;
import net.oschina.archx.spring.sequoiadb.SequoiaFactory;
import net.oschina.archx.spring.sequoiadb.SequoiaSession;
import net.oschina.archx.spring.sequoiadb.utils.SequoiaSQLHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 巨杉数据库持久化操作模板
 *
 * @author Archx
 * @date 2015/6/30 0030
 */
public class SequoiaSessionTemplate implements SequoiaSession {

    private final Logger log = LoggerFactory.getLogger(getClass());

    private SequoiaFactory sequoiaFactory;

    public SequoiaSessionTemplate(SequoiaFactory sequoiaFactory) {
        this.sequoiaFactory = sequoiaFactory;
    }

    /**
     * 绑定参数
     *
     * @param sql    语句
     * @param params 参数
     * @return 新语句
     */
    protected String bindParameters(String sql, Object... params) {
        return SequoiaSQLHelper.preparedStatement(sql, params);
    }

    @Override
    public Sequoiadb getSequoiadb() {
        try {
            return sequoiaFactory.getInstance();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean checkConfig() throws Exception {
        if (sequoiaFactory == null) {
            throw new RuntimeException("必须配置巨杉数据库工厂类!");
        }
        return true;
    }

    @Override
    public void execute(String sql) {
        log.debug("执行语句 - {}", sql);
        getSequoiadb().execUpdate(sql);
    }

    @Override
    public void execute(String sql, Object param) {
        String _sql = bindParameters(sql, param);
        log.debug("执行语句 - {}", _sql);
        getSequoiadb().execUpdate(_sql);
    }

    @Override
    public void execute(String sql, Object... params) {
        String _sql = bindParameters(sql, params);
        log.debug("执行语句 - {}", _sql);
        getSequoiadb().execUpdate(_sql);
    }

    @Override
    public DBCursor exec(String sql) {
        log.debug("执行语句 - {}", sql);
        return getSequoiadb().exec(sql);
    }

    @Override
    public void beginTransaction() {
        getSequoiadb().beginTransaction();
    }

    @Override
    public void commit() {
        getSequoiadb().commit();
    }

    @Override
    public void rollback() {
        getSequoiadb().rollback();
    }
}
